package com.rtx.wms.std.storer.handle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.common.EdiBeanUtils;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.std.common.bean.Storer;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.storer.service.StorerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StorerSchedulerHandle {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	StorerService storerService;
	
    @Autowired
    private CommonService commonService;
	
	public void handle(List<Storer> list) {
		//List<Storer> list = storerService.queryDistributeStorer("enterprise");
		
		List<String> whseidList = commonService.selectActiveWhseidNotEnterprise(WmsConstant.ENTERPRISE);
		
		for(Storer storer:list) {
			
			String msg = "ok";
			for(String whseid:whseidList) {
				if(!whseid.startsWith("wmwhse")) {
					continue;
				}
				
				try {
					storerService.addAndUpdataStorer(whseid, storer);
				} catch (Exception e) {
					log.error("仓库-{}-同步贸易伙伴异常",whseid);
					msg = e.getMessage();
				}
			}
			storerService.updDistributeStorerStatus("enterprise", msg, storer);
		}
	}

	/**
	 * 获取中间表数据
	 * @param whseid 仓库
	 * @param bo API配置
	 * @return 转化后的数据
	 */
	@DataSourceAnnotation
    public List<Storer> queryStorer(String whseid, ApiMappingInfoBo bo) {
		QueryWrapper<Storer> qw = Wrappers.query();
		qw.eq("ediflag", "P");
		qw.last("limit 500");
		return convertToConfigStorer(bo,qw);
    }

	private List<Storer> convertToConfigStorer(ApiMappingInfoBo bo, QueryWrapper<Storer> qw){
		List<Storer> head = new ArrayList<>();
		try {
			String apiid =  bo.getTargetApi().getId()+"";
			Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

			if(map != null && map.get("main") != null) {
				Class headclass = map.get("main");
				qw.select(EdiBeanUtils.getCoulmns(headclass));
				List<Map<String, Object>> oriData = storerService.listMaps(qw);
				for(Map<String, Object> dataMap:oriData) {
					Storer storer =(Storer) EdiBeanUtils.copyFields(dataMap, headclass);
					head.add(storer);
				}
			}else {
				head = storerService.list(qw);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return head;
	}
}
